import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/profile/model/notification_config_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:settings_ui/settings_ui.dart';

import '../../../common/constants/app_constants.dart';

/// 消息设置页面
class NotificationSettingPage extends ConsumerStatefulWidget {
  const NotificationSettingPage({super.key});

  @override
  ConsumerState<NotificationSettingPage> createState() => _NotificationSettingPageState();
}

class _NotificationSettingPageState extends ConsumerState<NotificationSettingPage> {
  bool mainSwitch = false;
  bool voicemainSwitch = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build执行完成后回调
      _checkVoiceNoticeState();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchConfig() async {
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    final res = await get<NotificationConfigResp, NotificationConfigResp>('/deviceAlarm/config/${deviceInfo.imei}',
        decodeType: NotificationConfigResp());
    res.when(success: (NotificationConfigResp resp) {
      if (resp.code == 200) {
        setState(() {
          mainSwitch = resp.data!.mainSwitch!;
        });
        _configVoiceStatusNotice();
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取消息配置失败 code: $code msg: $msg');
    });
  }
  _checkVoiceNoticeState() async {
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    final res = await get<BaseResp, BaseResp>('$newBaseULr/alarm/${deviceInfo.imei}',
        decodeType: BaseResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        setState(() {
          XLogger.info(resp.data['sound']);
          if (resp.data['sound'] == 1) {
            voicemainSwitch = true;
          }else {
            voicemainSwitch = false;
          }
          if (resp.data['status'] == 1) {
            mainSwitch = true;
          }else{
            mainSwitch = false;
          }
        });
        _updateConfig();
      }
    }, failure: (String msg, int code) {
      XLogger.error('更新已读状态失败 code: $code msg: $msg');
    });
  }
  _configVoiceStatusNotice() async {
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
      'status': mainSwitch ? "1" : "0",
      // 'status': "",
    };
    final res = await post<BaseResp, BaseResp>('$newBaseULr/alarm/update', data: queryParams, decodeType: BaseResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('更新已读状态失败 code: $code msg: $msg');
    });
  }
  _configVoiceNotice() async {
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
      'sound': voicemainSwitch ? "1" : "0",
      // 'status': "",
    };
    final res = await post<BaseResp, BaseResp>('$newBaseULr/alarm/update', data: queryParams, decodeType: BaseResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('更新已读状态失败 code: $code msg: $msg');
    });
  }
  _updateConfig() async {
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'mainSwitch': mainSwitch ? '1' : '0',
      'sos': mainSwitch ? '1' : '0',
      'speeding': mainSwitch ? '1' : '0',
      'lowPower': mainSwitch ? '1' : '0',
      'externalPowerDisconnect': mainSwitch ? '1' : '0',
      'vibration': mainSwitch ? '1' : '0',
      'lightSensitive': mainSwitch ? '1' : '0',
      'enterFence': mainSwitch ? '1' : '0',
      'leaveFence': mainSwitch ? '1' : '0',
    };
    final res = await post<BaseResp, BaseResp>('/deviceAlarm/subscribe', data: postData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      if (resp.code == 200) {
        XLogger.info('更新消息配置成功');
        _configVoiceStatusNotice();
      } else {
        ToastUtils.showToast('更新消息配置失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('更新消息配置失败');
      XLogger.error('更新消息配置失败 code: $code msg: $msg');
    });
  }



  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: const Text(
          '消息设置',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        backgroundColor: AppTheme.themeConfig.primaryColor,
        leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: const Icon(
              Icons.arrow_back,
              color: Colors.white,
              size: 24,
            )),
      ),
      child: SafeArea(
        bottom: false,
        child: SettingsList(
          applicationType: ApplicationType.cupertino,
          platform: DevicePlatform.iOS,
          sections: [
            SettingsSection(

              tiles: [
                SettingsTile.switchTile(
                  initialValue: mainSwitch,
                  onToggle: (bool value) {
                    setState(() {
                      mainSwitch = value;
                    });
                    if (value) {
                      // 申请通知权限
                      PermissionManager.requestNotificationPermissions();
                    }
                    _updateConfig();
                  },
                  title: const Text('接收告警通知'),
                  onPressed: (BuildContext context) {},
                ),

                SettingsTile.switchTile(
                  initialValue: voicemainSwitch,
                  onToggle: (bool value) {
                    setState(() {
                      voicemainSwitch = value;
                    });
                    if (value) {
                      // 申请通知权限
                      PermissionManager.requestNotificationPermissions();
                    }
                    _configVoiceNotice();
                  },
                  title: const Text('声音报警'),
                  onPressed: (BuildContext context) {},
                ),
              ],
            ),

          ],
        ),
      ),
    );
  }
}
